package com.finger.gulimall.coupon.exception;

import com.finger.common.exception.BizCodeEnume;
import com.finger.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(Exception.class)
    public R globalExceptionHandle(Throwable e) {
        e.printStackTrace();
        return R.error(10000, e.getMessage());

    }

    @ExceptionHandler(CouponException.class)
    public R productExceptionHandle(CouponException e) {
        e.printStackTrace();
        return R.error(e.getCode(), e.getMessage());

    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map<String, Object> respMap = new HashMap<>();
        ;
        if (result.hasErrors()) {
            result.getAllErrors().forEach(item -> {
                FieldError fieldError = result.getFieldError();
                respMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            });

        }
        return R.error(BizCodeEnume.VALID_EXCEPTION).put("data", respMap);
    }
}
